package com.xbai.springcloud.controller;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.xbai.springcloud.entity.CommonResult;
import com.xbai.springcloud.entity.Payment;
import com.xbai.springcloud.service.PaymentService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author xbai
 * @Date 2021/6/11
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/consumer")
public class CircleBreakerController {

    private static final String SERVER_URL = "http://nacos-payment-provider";

    private final RestTemplate restTemplate;

    private final PaymentService paymentService;

    @GetMapping("/fallback/{id}")
//    @SentinelResource(value = "fallback") // 没有配置
//    @SentinelResource(value = "fallback", fallback = "handlerFallback") // fallback 只负责处理业务异常
//    @SentinelResource(value = "fallback", blockHandler = "blockFallback") // blockHandler 只负责处理 Sentinel 控制台配置违规
//    @SentinelResource(value = "fallback", blockHandler = "blockFallback", fallback = "handlerFallback",
//            exceptionsToIgnore = {IllegalArgumentException.class}) // fallback 只负责处理业务异常
    public CommonResult<Payment> fallback(@PathVariable("id") Long id) {
        return paymentService.paymentSQL(id);
       /* CommonResult<Payment> result = restTemplate.getForObject(SERVER_URL + "/paymentSQL/" + id, CommonResult.class);
        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException，非法参数异常......");
        } else if (result.getData() == null) {
            throw new NullPointerException("NullPointerException，该 ID 没有对应记录，空指针异常......");
        }
        return result;*/
    }

    public CommonResult<Payment> blockFallback(@PathVariable("id") Integer id, BlockException e) {
        Payment payment = new Payment(id, null);
        return new CommonResult<>(445, "blockFallback-sentinel 限流，无此流水， BlockException " + e.getMessage(), payment);
    }

    public CommonResult<Payment> handlerFallback(@PathVariable("id") Integer id, Throwable e) {
        Payment payment = new Payment(id, null);
        return new CommonResult<>(444, "兜底异常 handlerFallback， exception 内容 " + e.getMessage(), payment);
    }
}
